//
//  ViewController.m
//  UIAccelerometer
//
//  Created by 董文博 on 15/2/10.
//
//

#import "ViewController.h"
#import "UIView+Extension.h"

@interface ViewController ()<UIAccelerometerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *ball;
@property (assign, nonatomic) CGPoint volecity;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //获得单例对象
    UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
    //设置代理
    accelerometer.delegate = self;
    //设置采样间隔 1/60.0 就是 1秒采集60次
    accelerometer.updateInterval = 1 / 60.0;
}

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    //速度等于加速度的累加
    _volecity.x += acceleration.x;
    _volecity.y += acceleration.y;
    //位移等于速度的累加
    self.ball.x += _volecity.x;
    self.ball.y -= _volecity.y;
    
    //边界检测
    if(self.ball.x<=0){
        self.ball.x = 0;
        //加入反弹，削弱速度
        _volecity.x *= -0.5;
    }
    if (self.ball.y<=0) {
        self.ball.y = 0;
        _volecity.y *= -0.5;
    }
    if (self.ball.maxX>=self.view.width) {
        self.ball.maxX = self.view.width;
        _volecity.x *= -0.5;
    }
    if (self.ball.maxY>=self.view.height) {
        self.ball.maxY = self.view.height;
        _volecity.y *= -0.5;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
